package com.example.lettcode._202409._20240914;

import java.util.Arrays;

public class Lun_zhuan_shu_zu {
    public static void main(String[] args) {
        int[] nums = {1, 2};
        int k = 3;
        Arrays.stream(nums).forEach(num -> System.out.print(num + " "));
        System.out.println();
        rotate3(nums, k);
        Arrays.stream(nums).forEach(num -> System.out.print(num + " "));
    }


    public static void rotate(int[] nums, int k) {
        if (k == 0) {
            return;
        }

        if (k > nums.length && nums.length % k == 0) {
            return;
        }

        // 不论K有多大，最终只轮换这么多次
        int tmp_k = nums.length < k ? k % nums.length : k;

        int[] tmp_num = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int m = i + tmp_k > nums.length - 1 ? i + tmp_k - nums.length  : i + tmp_k;
            tmp_num[m] = nums[i];
        }

        for (int i = 0; i < nums.length; i++) {
            nums[i] = tmp_num[i];
        }
    }

    public static void rotate2(int[] nums, int k) {
        int[] tmp_num = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            tmp_num[(i + k) % nums.length] = nums[i];
        }
        System.arraycopy(tmp_num, 0, nums, 0, nums.length);
    }


    public static void rotate3(int[] nums, int k) {
        int tmp_k = k % nums.length;
        reveser(nums, 0, nums.length - 1);
        reveser(nums, 0, tmp_k - 1);
        reveser(nums, tmp_k, nums.length - 1);
    }

    private static void reveser(int[] nums, int start, int end) {
        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] =tmp;
            start++;
            end--;
        }
    }


}
